package com.chunuo.blogs.controller;

import com.chunuo.blogs.entity.User;
import com.chunuo.blogs.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 类的作用
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-05-14 16:42
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 登录功能
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user){
        System.out.println(user);
        Map<String,Object> map = new HashMap<>();
        Subject currnet = SecurityUtils.getSubject();
        if(!currnet.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
            if(user.getMe()!=null){
                token.setRememberMe(true);
            }
            try {
                currnet.login(token);
                map.put("status",1);
            } catch (AuthenticationException e) {
                map.put("status",0);
                map.put("msg",e.getMessage());
            }
        }

        return map;
    }


    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/find")
    public String find(@RequestParam("id") Integer id){
        String byId = userService.findById(id);
        return byId;
    }

}
